<template>
  <view class="image-gallery-container">
    <!-- 顶部导航 -->
    <view class="gallery-header">
      <text class="gallery-title">图片画廊</text>
      <text class="gallery-subtitle">探索精彩瞬间</text>
    </view>
    
    <!-- 图片瀑布流 -->
    <view class="image-waterfall" v-if="images.length > 0">
      <view class="waterfall-column" v-for="column in 2" :key="column">
        <view class="image-item" v-for="(image, index) in getColumnImages(column)" :key="image.ID">
          <view class="image-wrapper" @click="previewImage(image)">
            <image 
              :src="image.image_url" 
              mode="aspectFill"
              class="gallery-image"
            />    
          </view>
          <view class="image-info">
            <text class="image-title">{{ image.title || '未命名图片' }}</text>
            <view class="image-stats">
              <text class="stat-item">👁 {{ image.views || 0 }}</text>
              <text class="stat-item">❤️ {{ image.likes_count || 0 }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 空状态 -->
    <view class="empty-state" v-else-if="!loading">
      <image src="/static/icons/empty.png" class="empty-image" mode="aspectFit"/>
      <text class="empty-text">暂无图片</text>
      <text class="empty-subtext">快来上传您的第一张图片吧</text>
    </view>
    
    <!-- 加载状态 -->
    <view class="loading-state" v-if="loading">
      <view class="loading-spinner-large"></view>
      <text class="loading-text">加载中...</text>
    </view>
    
    <!-- 加载更多 -->
    <view class="load-more" v-if="hasMore && images.length > 0">
      <view class="loading-spinner" v-if="loadingMore"></view>
      <text class="load-more-text" v-else @click="loadMoreImages">上拉加载更多</text>
    </view>
    
    <!-- 到底提示 -->
    <view class="end-tip" v-if="!hasMore && images.length > 0">
      <text>已经到底啦</text>
    </view>
  </view>
</template>

<script>
import { getImageList } from '@/utils/api'

export default {
  data() {
    return {
      images: [],
      loading: true,
      loadingMore: false,
      hasMore: true,
      currentPage: 1,
      pageSize: 12,
      total: 0,
      placeholderImage: '/static/logo.png',
      // 模拟数据，当API调不通时使用
      mockImages: [
        {
          ID: 1,
          title: '美丽风景',
          image_url: 'https://picsum.photos/400/600?random=1',
          views: 1234,
          likes_count: 56
        },
        {
          ID: 2,
          title: '城市建筑',
          image_url: 'https://picsum.photos/400/500?random=2',
          views: 2345,
          likes_count: 78
        },
        {
          ID: 3,
          title: '自然奇观',
          image_url: 'https://picsum.photos/400/700?random=3',
          views: 3456,
          likes_count: 90
        },
        {
          ID: 4,
          title: '美食分享',
          image_url: 'https://picsum.photos/400/400?random=4',
          views: 4567,
          likes_count: 102
        },
        {
          ID: 5,
          title: '旅行记忆',
          image_url: 'https://picsum.photos/400/650?random=5',
          views: 5678,
          likes_count: 114
        },
        {
          ID: 6,
          title: '艺术创作',
          image_url: 'https://picsum.photos/400/550?random=6',
          views: 6789,
          likes_count: 126
        },
        {
          ID: 7,
          title: '科技前沿',
          image_url: 'https://picsum.photos/400/580?random=7',
          views: 7890,
          likes_count: 138
        },
        {
          ID: 8,
          title: '生活瞬间',
          image_url: 'https://picsum.photos/400/620?random=8',
          views: 8901,
          likes_count: 150
        }
      ]
    }
  },
  onLoad() {
    // 页面加载时获取图片列表
    this.fetchImages()
  },
  onReachBottom() {
    // 上拉加载更多
    if (!this.loadingMore && this.hasMore) {
      this.loadMoreImages()
    }
  },
  methods: {
    // 获取图片列表
    async fetchImages() {
      this.loading = true
      try {
        // 尝试调用API获取数据
        const params = {
          page: this.currentPage,
          pageSize: this.pageSize
        }
        
        try {
          const result = await getImageList(params)
          console.log('getImageList API返回数据:', result)
          this.images = result.images || []
          this.total = result.total || 0
          this.hasMore = this.images.length < this.total
          
          // 为每张图片添加加载状态
          this.images.forEach(image => {
            image.loaded = false
          })
        } catch (apiError) {
          console.warn('API调用失败，使用模拟数据:', apiError)
          // 使用模拟数据
          this.images = this.mockImages
          this.hasMore = false
          
          // 为每张模拟图片添加加载状态
          this.images.forEach(image => {
            image.loaded = false
          })
        }
      } catch (error) {
        console.error('获取图片列表失败:', error)
        uni.showToast({
          title: '获取图片失败',
          icon: 'none',
          duration: 2000
        })
        
        // 使用模拟数据作为备选
        this.images = this.mockImages
        this.hasMore = false
      } finally {
        this.loading = false
      }
    },
    
    // 加载更多图片
    async loadMoreImages() {
      if (this.loadingMore || !this.hasMore) {
        return
      }
      
      this.loadingMore = true
      try {
        const params = {
          page: this.currentPage + 1,
          pageSize: this.pageSize
        }
        
        try {
          const result = await getImageList(params)
          const newImages = result.images || []
          
          // 为新图片添加加载状态
          newImages.forEach(image => {
            image.loaded = false
          })
          
          this.images = [...this.images, ...newImages]
          this.currentPage++
          this.hasMore = this.images.length < (result.total || this.total)
        } catch (apiError) {
          console.warn('加载更多API调用失败，使用模拟数据:', apiError)
          // 模拟加载更多
          const newMockImages = this.mockImages.map(img => ({
            ...img,
            id: img.id + this.currentPage * 100,
            image_url: img.image_url.replace('random=', `random=${img.id + this.currentPage * 100}`)
          }))
          
          // 为新图片添加加载状态
          newMockImages.forEach(image => {
            image.loaded = false
          })
          
          this.images = [...this.images, ...newMockImages]
          this.currentPage++
          // 模拟数据只加载一次
          this.hasMore = false
        }
      } catch (error) {
        console.error('加载更多图片失败:', error)
        uni.showToast({
          title: '加载更多失败',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loadingMore = false
      }
    },
    
    // 获取指定列的图片 - 改进为基于ID的分配，确保一致性
    getColumnImages(column) {
      return this.images.filter((image) => {
        // 使用ID的奇偶性来分配图片，确保即使列表变化，图片仍会显示在相同列
        return (image.ID || image.id) % 2 === (column - 1)
      })
    },
    
    // 图片加载完成回调 - 改进为基于ID查找，避免索引问题
    onImageLoad(image) {
     // console.log('图片加载完成:', image)
      const index = this.images.findIndex(img => img.ID === image.ID || img.id === image.id)
      if (index !== -1) {
        this.$set(this.images[index], 'loaded', true)
      }
    },
    
    // 预览图片
    previewImage(image) {
      const urls = this.images.map(img => img.image_url)
      const currentIndex = this.images.findIndex(img => img.ID === image.ID)
      
      uni.previewImage({
        current: currentIndex,
        urls: urls,
        indicator: 'number',
        loop: true
      })
    }
  }
}
</script>

<style scoped>
.image-gallery-container {
  background: #f8f8f8;
  min-height: 100vh;
}

.gallery-header {
  padding: 60rpx 20rpx 40rpx;
  text-align: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  position: relative;
  overflow: hidden;
}

.gallery-header::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: radial-gradient(circle at 50% 50%, rgba(255, 255, 255, 0.15) 0%, rgba(255, 255, 255, 0) 60%);
}

.gallery-title {
  font-size: 48rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  display: block;
  position: relative;
  z-index: 1;
}

.gallery-subtitle {
  font-size: 28rpx;
  opacity: 0.9;
  position: relative;
  z-index: 1;
}

.image-waterfall {
  display: flex;
  padding: 20rpx;
  gap: 20rpx;
}

.waterfall-column {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.image-item {
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.image-item:active {
  transform: scale(0.98);
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.12);
}

.image-wrapper {
  position: relative;
  width: 100%;
  background: #f5f5f5;
}

.gallery-image {
  width: 100%;
  height: 200rpx;
  border-radius: 16rpx 16rpx 0 0;
  transition: opacity 0.3s ease;
}

.image-placeholder {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f5f5;
}

.image-info {
  padding: 20rpx;
}

.image-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-stats {
  display: flex;
  gap: 20rpx;
}

.stat-item {
  font-size: 22rpx;
  color: #999;
}

.empty-state {
  padding: 120rpx 40rpx;
  text-align: center;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin: 0 auto 40rpx;
  opacity: 0.5;
}

.empty-text {
  font-size: 36rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.empty-subtext {
  font-size: 28rpx;
  color: #999;
}

.loading-state {
  padding: 120rpx 40rpx;
  text-align: center;
}

.loading-spinner {
  width: 40rpx;
  height: 40rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}

.loading-spinner-large {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #999;
}

.load-more {
  padding: 40rpx 0;
  text-align: center;
}

.load-more-text {
  font-size: 28rpx;
  color: #667eea;
}

.end-tip {
  padding: 40rpx 0;
  text-align: center;
}

.end-tip text {
  font-size: 26rpx;
  color: #999;
}
</style>